<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Shop\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Address;

class AddressController extends Controller
{
    /***
     * 地址列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $addresses = Address::where('customer_id', session('wechat.customer.id'))->get();
        return view('wechat.addresses.index', compact('addresses'));
    }


    /***
     * 新建地址
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('wechat.addresses.create');
    }


    /***
     * 保存地址
     * @param Request $request
     */
    public function store(Request $request)
    {
        $pca = explode(" ", $request->pca);

        Address::create([
            'customer_id' => session('wechat.customer.id'),
            'name' => $request->name,
            'province' => $pca[0],
            'city' => $pca[1],
            'area' => $pca[2],
            'tel' => $request->tel,
            'detail' => $request->detail,
        ]);
    }


    /***
     * 设置默认地址
     * @param Request $request
     */
    public function default_address(Request $request)
    {
        Customer::where('id', session('wechat.customer.id'))->update(['address_id' => $request->address_id]);

        //重新设置session
        $customer = session()->get('wechat.customer');
        $customer['address_id'] = $request->address_id;
        session()->put('wechat.customer', $customer);
    }


    /***
     * 用户中心---地址管理
     */
    public function manage()
    {
        $addresses = Address::where('customer_id', session('wechat.customer.id'))->get();
        return view('wechat.addresses.manage', compact('addresses'));
    }


    /***
     * 用户中心---编辑地址
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $address = Address::find($id);
        return view('wechat.addresses.edit', compact('address'));
    }


    /***
     * 用户中心---保存编辑地址
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        $pca = explode(" ", $request->pca); //把提交过来的省市区字符串拆分成数组
        Address::where('id', $id)
            ->update([
                'name' => $request->name,
                'province' => $pca[0],
                'city' => $pca[1],
                'area' => $pca[2],
                'tel' => $request->tel,
                'detail' => $request->detail,
            ]);

    }

    /***
     * 用户中心---删除地址
     * @param $id
     */
    public function destroy($id)
    {
        Address::destroy($id);
        return back();
    }

}
